package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 猛在王
 * @version 1.0
 * @date 29/6/2024 上午10:25
 * @description OrderTask
 * @since 1.0
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 支付超时自动取消订单
     */
    @Scheduled(cron = "* 1 * * * ?")
    public void paymentTimeOut(){
        log.info("处理订单支付超时，{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //根据订单状态和订单时间来查询订单
        List<Orders> orders = orderMapper.selectByStatusAndTime(Orders.PENDING_PAYMENT,time);
        //更改订单状态
        if (orders != null){
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单支付超时，自动取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }

    /**
     * 派送超时
     */
    @Scheduled(cron = "* * 1 * * ?")
    public void deliveryTimeOut(){
        log.info("派送超时，{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        //根据订单状态和订单时间来查询订单
        List<Orders> orders = orderMapper.selectByStatusAndTime(Orders.DELIVERY_IN_PROGRESS,time);
        //更改订单状态
        if (orders != null){
            for (Orders order : orders) {
                order.setStatus(Orders.COMPLETED);
                order.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }


}
